function trim (myString) {
  return myString.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

function appendItemToSelectedGallery(id) {
  jQuery('#selectedGallery').append(itemsToAddOnSelectedGallery[id]);
  jQuery('#result').val(jQuery('#selectedGallery').html());
}  

var scriptLoader = {
	_loadScript: function (url, callback) {
		var head = document.getElementsByTagName('head')[0];
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = url;
		if (callback) {
			script.onreadystatechange = function () {
				if (this.readyState == 'loaded') callback();
			}
			script.onload = callback;
		}
		head.appendChild(script);
	},

	load: function (items, iteration) {
		if (!iteration) iteration = 0;
		if (items[iteration]) {
			scriptLoader._loadScript(
				items[iteration],
				function () {
					scriptLoader.load(items, iteration+1);
				}
			)
		}
	}
}

var itemsToAddOnSelectedGallery = new Object();

var picasa = {
 
	galleries: 0,
 
	gallery: function (galleryObjectId, galleryObjectName, settings) {
		this.galleryObjectId = galleryObjectId;
		this.galleryObjectName = galleryObjectName;
		this.containerId = settings.containerId;
		this.userName = settings.userName;
		this.albumName = settings.albumName;
		this.imageSize = settings.imageSize;
		this.itemsArray = [];
		this.imageMaxNumber = settings.imageMaxNumber;
		this.imageOrderAntechrono = settings.imageOrderAntechrono;
		this.allImages = settings.allImages;
		this.galleryId = settings.galleryId;
 
		this.setup = function (data) {
		
			this.itemsArray = data.feed.entry;
			this.totalItems = this.itemsArray.length;

      // définition de l'index de la première image à afficher
			var imageLastIndex;
			if (this.imageOrderAntechrono) {
 			  if (this.imageMaxNumber > 0 && this.totalItems > this.imageMaxNumber) {
 				 imageLastIndex = this.totalItems - this.imageMaxNumber - 1;
 			  } else {
 				 imageLastIndex = 0;
 			  }
 			} else {
 			  if (this.imageMaxNumber > 0 && this.totalItems > this.imageMaxNumber) {
 				 imageLastIndex = this.imageMaxNumber;
 			  } else {
 				 imageLastIndex = this.totalItems;
 			  }
      }
 			
 			// définition de l'index de la dernière image à afficher
 			var imageFirstIndex;
      if (this.imageOrderAntechrono) {
        imageFirstIndex = this.totalItems - 1;
      } else {
        imageFirstIndex = 0;
      } 			

      // parcours de toutes les images       			
 			for (var x = imageFirstIndex; (this.imageOrderAntechrono) ? x >= imageLastIndex : x < imageLastIndex ; (this.imageOrderAntechrono) ? x-- : x++) {
 			  
 			  var mustDisplayThisImage = this.allImages;
 			  
 			  // parcours des tags de l'image 
 			  if (this.itemsArray[x].media$group.media$keywords.$t != undefined) {
 			  
          var tags = this.itemsArray[x].media$group.media$keywords.$t.split(',');
          var isHtmlUrlTag = new RegExp("^http");
          var tagHtmlUrl;
           
 			    for (var tagIndex = 0; tagIndex < tags.length; tagIndex++) {
 			    
 			      // récupération de l'URL sur laquelle doit pointer l'image si proposé
 			      if (isHtmlUrlTag.test(trim(tags[tagIndex]))) {
 			        tagHtmlUrl = trim(tags[tagIndex]); 			        
            }

            // si un tag correspond à l'identifiant de la gallerie, c'est qu'il faut afficher l'image            
            if(!mustDisplayThisImage && trim(tags[tagIndex]) == this.galleryId) {
              mustDisplayThisImage = true;                            
            }
          }
        }

        // définition du lien à placer sur l'image
        var itemUrl;        
        if (tagHtmlUrl == undefined) {
        
          // lien vers une image redimensionnée en dehors de picasa
          // itemUrl = this.itemsArray[x].media$group.media$content[0].url;
          
          // recherche du lien vers de la photo vers l'album Picasa
          var linkToPicasa;
          var isPicasaUrl = new RegExp("^https://picasaweb\.google\.com/[0-9]+/.+#[0-9]+$");          
          for (var i = 0; i < this.itemsArray[x].link.length; i++) {
            if(isPicasaUrl.test(this.itemsArray[x].link[i].href)) {
                linkToPicasa = this.itemsArray[x].link[i].href;
            }            
          }
          
          itemUrl = linkToPicasa;
          
        } else {
          itemUrl = tagHtmlUrl; 
        }

        if (mustDisplayThisImage) {                

          // conservation du code html final à ajouter si l'image est sélectionnée          
          itemsToAddOnSelectedGallery[this.itemsArray[x].id.$t] = '<div onClick="document.location.href=\'' + itemUrl + '\'" class="picasaGalleryItem" style="cursor: pointer; width: ' + this.imageSize + 'px; height: ' + this.imageSize + 'px; background: url(' + this.itemsArray[x].media$group.media$thumbnail[0].url + ') no-repeat center center; "></div>\n';
          
          // ajout du code permettant de sélectionner l'image
				  jQuery('#' + this.containerId).append('<div onClick="appendItemToSelectedGallery(\''+this.itemsArray[x].id.$t+'\');" class="picasaGalleryItem" style="cursor: pointer; width: ' + this.imageSize + 'px; height: ' + this.imageSize + 'px; background: url(' + this.itemsArray[x].media$group.media$thumbnail[0].url + ') no-repeat center center; "></div>\n');
				}
			}
		};
 
	},
 
	load: function (settings) {
		var galleryObjectId = picasa.galleries++;
		var galleryObjectName = 'picasa.gallery' + galleryObjectId;
		var galleryObject = eval(galleryObjectName + ' = new picasa.gallery(galleryObjectId, galleryObjectName, settings)');
 
		scriptLoader.load([
			'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
			'http://picasaweb.google.com/data/feed/base/user/' + galleryObject.userName + '/albumid/' + galleryObject.albumName + '?alt=json-in-script&callback=' + galleryObjectName + '.setup&kind=photo&thumbsize=' + galleryObject.imageSize
		]);
	}
}

picasa.load({
  containerId: 'picasaHeaderGallery',
  userName: '102986910814924582742',
  albumName: '5729824277720341441',
  imageSize: 104,
  imageMaxNumber: 0,
  imageOrderAntechrono: true,
  allImages: true
});
			
/*picasa.load({
				containerId: 'picasaPartialGallery',
				userName: '102986910814924582742',
				albumName: '5604015092127304497',
				imageSize: 104,
				imageMaxNumber: 0,
				imageOrderAntechrono: false,
				allImages: true,
				galleryId: '20120413'
			});*/